About the project

I went to the R-courses last fall and even though it was really difficult to me and lot of hard work needed, I really got excited and now Im here again feeling very uncertain but at the same time very motivated to learn. Here is the link to my IODS project in GitHub https://github.com/madmintt/IODS-project


REGRESSION AND MODEL VALIDATION

This week I have learned to draw advanced scatterplots and some new things about the diagnostics of regressionmodel.

## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
## 
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
## 
##     nasa
learning2014 <-read.csv("create_learning2014.csv", TRUE, ",")
summary(learning2014)
##       X.3              X.2              X.1               X         
##  Min.   :  1.00   Min.   :  1.00   Min.   :  1.00   Min.   :  1.00  
##  1st Qu.: 42.25   1st Qu.: 42.25   1st Qu.: 42.25   1st Qu.: 42.25  
##  Median : 83.50   Median : 83.50   Median : 83.50   Median : 83.50  
##  Mean   : 83.50   Mean   : 83.50   Mean   : 83.50   Mean   : 83.50  
##  3rd Qu.:124.75   3rd Qu.:124.75   3rd Qu.:124.75   3rd Qu.:124.75  
##  Max.   :166.00   Max.   :166.00   Max.   :166.00   Max.   :166.00  
##  gender       Age           Attitude          deep            stra      
##  F:110   Min.   :17.00   Min.   :1.400   Min.   :1.583   Min.   :1.250  
##  M: 56   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333   1st Qu.:2.625  
##          Median :22.00   Median :3.200   Median :3.667   Median :3.188  
##          Mean   :25.51   Mean   :3.143   Mean   :3.680   Mean   :3.121  
##          3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083   3rd Qu.:3.625  
##          Max.   :55.00   Max.   :5.000   Max.   :4.917   Max.   :5.000  
##       surf           Points     
##  Min.   :1.583   Min.   : 7.00  
##  1st Qu.:2.417   1st Qu.:19.00  
##  Median :2.833   Median :23.00  
##  Mean   :2.787   Mean   :22.72  
##  3rd Qu.:3.167   3rd Qu.:27.75  
##  Max.   :4.333   Max.   :33.00

This data includes 166 observations and seven variables, witch are gender, age, attitude (towards statistics) and three different studyingstrategies -or skills; deep, surface and strategic. The data includes also the exam points -variable, whitch we consider here the indicator of learning statistics.

VISUALIZING THE DATA

Plot matrix of the variables

visual_d <- ggpairs(learning2014, mapping = aes(col = gender, alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))
visual_d

pa <- ggplot(learning2014, aes(x = Attitude, y = Points, col = gender))
pat <- pa + geom_point()
patt <-pat + geom_smooth(method = "lm")
patti <-patt + ggtitle("Attitude vs. points")
patti

There seems to be a positive connection between attitude and points.

pd <- ggplot(learning2014, aes(x = deep, y = Points, col = gender))
pde <- pd + geom_point()
pdee <- pde + geom_smooth(method = "lm")
pdeep <- pdee + ggtitle("Deep vs. points")
pdeep

There seems to be absolutely no connection between deep and points.

pst <- ggplot(learning2014, aes(x = stra, y = Points, col = gender))
pstr <- pst + geom_point()
pstra <- pstr + geom_smooth(method = "lm")
pstrat <- pstra + ggtitle("Strategic vs. points")
pstrat

There might be a small positive connection between strategic and points.

psu <- ggplot(learning2014, aes(x = surf, y = Points, col = gender))
psur <- psu + geom_point()
psurf <- psur + geom_smooth(method = "lm")
psurfa <- psurf + ggtitle("Surface vs. points")
psurfa

There could be a small negative connection between surface and points.

ika <- ggplot(learning2014, aes(x = Age, y = Points, col = gender))
ikak <- ika + geom_point()
ikak <- ika + geom_smooth(method = "lm")
ikaka <- ikak + ggtitle("Age vs. points")
ikaka

According to this it seems like age has something to do with the points in the malegroup.

my_regressionmodel <- lm(formula = Points ~ Attitude, data = learning2014)
summary(my_regressionmodel)
## 
## Call:
## lm(formula = Points ~ Attitude, data = learning2014)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.6372     1.8303   6.358 1.95e-09 ***
## Attitude      3.5255     0.5674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09

I did the regression analysis first with having attitude, strategic and surface-learning as explanatory variables, because they seemed to be the three most potential explanatories when looking at the plots. However, the regression analysis showed, that no other variables but attitude are explaining the exampoints with statistical significance, so I only left that in the final model. So the interpretation is that when attitude increases one unit, the exampoints increases 3.5 in average. The multiple R-square is 0.1906 whitch means that the model explains 19 % of the variance of the exampoints in this case.

Diagnostic plots

Every statistical model includes several assumptions. The linear regresssion model assumes first of all that the errors of the model are normally distributed. Another assumption of linear regression model is that the errors have a constant variance and that they are not dependent of the explanatory variables. By making diagnostic plots we can see if theese assumptions come true in our model.

par(mfrow = c(2,2))
plot(my_regressionmodel, which = c(1, 2, 5))

By looking at the diagnostic plot of Residuals vs. Fitted values, we can see, that the plots form no pattern, whitch means that the errors do not depend on the explanatory variable,so no problem in there. The QQplot shows a nice fit with the line interpreting that the errors are normally distributed. The value of leverage is very low 0.04, which means that there are no observations with unusual leverage.


LOGISTICAL REGRESSION

library(ggplot2)
library(dplyr)
library(tidyr)
library(boot)
alc <- read.csv("create_alc.csv", TRUE, ",")
summary(alc)
##        X          school   sex          age        address famsize  
##  Min.   :  1.00   GP:342   F:198   Min.   :15.00   R: 81   GT3:278  
##  1st Qu.: 96.25   MS: 40   M:184   1st Qu.:16.00   U:301   LE3:104  
##  Median :191.50                    Median :17.00                    
##  Mean   :191.50                    Mean   :16.59                    
##  3rd Qu.:286.75                    3rd Qu.:17.00                    
##  Max.   :382.00                    Max.   :22.00                    
##  Pstatus      Medu            Fedu             Mjob           Fjob    
##  A: 38   Min.   :0.000   Min.   :0.000   at_home : 53   at_home : 16  
##  T:344   1st Qu.:2.000   1st Qu.:2.000   health  : 33   health  : 17  
##          Median :3.000   Median :3.000   other   :138   other   :211  
##          Mean   :2.806   Mean   :2.565   services: 96   services:107  
##          3rd Qu.:4.000   3rd Qu.:4.000   teacher : 62   teacher : 31  
##          Max.   :4.000   Max.   :4.000                                
##         reason    nursery   internet    guardian     traveltime   
##  course    :140   no : 72   no : 58   father: 91   Min.   :1.000  
##  home      :110   yes:310   yes:324   mother:275   1st Qu.:1.000  
##  other     : 34                       other : 16   Median :1.000  
##  reputation: 98                                    Mean   :1.448  
##                                                    3rd Qu.:2.000  
##                                                    Max.   :4.000  
##    studytime        failures      schoolsup famsup     paid     activities
##  Min.   :1.000   Min.   :0.0000   no :331   no :144   no :205   no :181   
##  1st Qu.:1.000   1st Qu.:0.0000   yes: 51   yes:238   yes:177   yes:201   
##  Median :2.000   Median :0.0000                                           
##  Mean   :2.037   Mean   :0.2016                                           
##  3rd Qu.:2.000   3rd Qu.:0.0000                                           
##  Max.   :4.000   Max.   :3.0000                                           
##  higher    romantic      famrel         freetime        goout      
##  no : 18   no :261   Min.   :1.000   Min.   :1.00   Min.   :1.000  
##  yes:364   yes:121   1st Qu.:4.000   1st Qu.:3.00   1st Qu.:2.000  
##                      Median :4.000   Median :3.00   Median :3.000  
##                      Mean   :3.937   Mean   :3.22   Mean   :3.113  
##                      3rd Qu.:5.000   3rd Qu.:4.00   3rd Qu.:4.000  
##                      Max.   :5.000   Max.   :5.00   Max.   :5.000  
##       Dalc            Walc           health         absences   
##  Min.   :1.000   Min.   :1.000   Min.   :1.000   Min.   : 0.0  
##  1st Qu.:1.000   1st Qu.:1.000   1st Qu.:3.000   1st Qu.: 1.0  
##  Median :1.000   Median :2.000   Median :4.000   Median : 3.0  
##  Mean   :1.482   Mean   :2.296   Mean   :3.573   Mean   : 4.5  
##  3rd Qu.:2.000   3rd Qu.:3.000   3rd Qu.:5.000   3rd Qu.: 6.0  
##  Max.   :5.000   Max.   :5.000   Max.   :5.000   Max.   :45.0  
##        G1              G2              G3           alc_use     
##  Min.   : 2.00   Min.   : 4.00   Min.   : 0.00   Min.   :1.000  
##  1st Qu.:10.00   1st Qu.:10.00   1st Qu.:10.00   1st Qu.:1.000  
##  Median :12.00   Median :12.00   Median :12.00   Median :1.500  
##  Mean   :11.49   Mean   :11.47   Mean   :11.46   Mean   :1.889  
##  3rd Qu.:14.00   3rd Qu.:14.00   3rd Qu.:14.00   3rd Qu.:2.500  
##  Max.   :18.00   Max.   :18.00   Max.   :18.00   Max.   :5.000  
##   high_use      
##  Mode :logical  
##  FALSE:268      
##  TRUE :114      
##                 
##                 
## 
colnames(alc)
##  [1] "X"          "school"     "sex"        "age"        "address"   
##  [6] "famsize"    "Pstatus"    "Medu"       "Fedu"       "Mjob"      
## [11] "Fjob"       "reason"     "nursery"    "internet"   "guardian"  
## [16] "traveltime" "studytime"  "failures"   "schoolsup"  "famsup"    
## [21] "paid"       "activities" "higher"     "romantic"   "famrel"    
## [26] "freetime"   "goout"      "Dalc"       "Walc"       "health"    
## [31] "absences"   "G1"         "G2"         "G3"         "alc_use"   
## [36] "high_use"
gather(alc) %>% glimpse
## Warning: attributes are not identical across measure variables;
## they will be dropped
## Observations: 13,752
## Variables: 2
## $ key   <chr> "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "...
## $ value <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",...
alc1 <- gather(alc) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free")
## Warning: attributes are not identical across measure variables;
## they will be dropped
alc1 + geom_bar()

This data approach student achievement in secondary education of two Portuguese schools and the variables include student grades, demographic, social and school related features. In my analysis here my task is to study witch variables affect students consumption of alcohol and predict it. My hypothesis is that studytime relates to alcohol consumption so that the more you drink the less time you study. Alcohol consumption could also have something to do with failures and absences. My guess is also that bad familyrelations could encrease alcohol consumption.

Barplot of alcohol consumption by sex

g1 <- ggplot(data = alc, aes(x = high_use, fill = sex))
g1 + geom_bar()

Ggplot of alcohol consumption

g2 <- ggplot(data = alc, aes(x = high_use))
g3 <- g2 + geom_bar()
g4 <- g3 + facet_wrap("sex")
g4

The distribution of familyrelations and alcohol consumption

g1 <- ggplot(alc, aes(x = high_use, y = famrel,col = sex))
g1 + geom_boxplot() + ylab("famrel")

alc %>% group_by(sex, high_use, famrel) %>% summarise(count = n())
## # A tibble: 19 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use famrel count
##    <fct> <lgl>     <int> <int>
##  1 F     FALSE         1     5
##  2 F     FALSE         2     7
##  3 F     FALSE         3    24
##  4 F     FALSE         4    81
##  5 F     FALSE         5    39
##  6 F     TRUE          2     3
##  7 F     TRUE          3    12
##  8 F     TRUE          4    19
##  9 F     TRUE          5     8
## 10 M     FALSE         1     1
## 11 M     FALSE         2     3
## 12 M     FALSE         3    15
## 13 M     FALSE         4    54
## 14 M     FALSE         5    39
## 15 M     TRUE          1     2
## 16 M     TRUE          2     6
## 17 M     TRUE          3    13
## 18 M     TRUE          4    35
## 19 M     TRUE          5    16

By looking at the barplots it seems like there could be a relation between familyrelations and high use of alcohol; the familyrelations in the non-high use are higher. Same kind of evaluations seems possible when looking at the groopingtable as well.

The distributions of studytime and alcohol use

g1 <- ggplot(alc, aes(x = high_use, y = studytime,col = sex))
g1 + geom_boxplot() + ylab("studytime")

alc %>% group_by(sex, high_use, studytime) %>% summarise(count = n())
## # A tibble: 16 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use studytime count
##    <fct> <lgl>        <int> <int>
##  1 F     FALSE            1    18
##  2 F     FALSE            2    83
##  3 F     FALSE            3    39
##  4 F     FALSE            4    16
##  5 F     TRUE             1     9
##  6 F     TRUE             2    25
##  7 F     TRUE             3     7
##  8 F     TRUE             4     1
##  9 M     FALSE            1    40
## 10 M     FALSE            2    52
## 11 M     FALSE            3    13
## 12 M     FALSE            4     7
## 13 M     TRUE             1    33
## 14 M     TRUE             2    35
## 15 M     TRUE             3     1
## 16 M     TRUE             4     3

Studytime could also be connected to high use of alcohol, at least in femalegroups.

The distributions of failures and alcohol use

g1 <- ggplot(alc, aes(x = high_use, y = failures,col = sex))
g1 + geom_boxplot() + ylab("failures")

alc %>% group_by(sex, high_use, failures) %>% summarise(count = n())
## # A tibble: 15 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use failures count
##    <fct> <lgl>       <int> <int>
##  1 F     FALSE           0   143
##  2 F     FALSE           1     8
##  3 F     FALSE           2     5
##  4 F     TRUE            0    33
##  5 F     TRUE            1     7
##  6 F     TRUE            2     1
##  7 F     TRUE            3     1
##  8 M     FALSE           0   101
##  9 M     FALSE           1     4
## 10 M     FALSE           2     5
## 11 M     FALSE           3     2
## 12 M     TRUE            0    57
## 13 M     TRUE            1     5
## 14 M     TRUE            2     8
## 15 M     TRUE            3     2

What it comes to failures, the hypothesis may not be true; the distributions are looking quite the same in both high-drinkers and those who are not drinking too much. When looking at the table, there are 144 heavy drinkers with zero failiors, but in the other groub the numerus is 90, witch is quite high as well.

The distributions of absences and alcohol use

g1 <- ggplot(alc, aes(x = high_use, y = absences,col = sex))
g1 + geom_boxplot() + ylab("absences")

alc %>% group_by(sex, high_use, absences) %>% summarise(count = n())
## # A tibble: 66 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use absences count
##    <fct> <lgl>       <int> <int>
##  1 F     FALSE           0    28
##  2 F     FALSE           1    17
##  3 F     FALSE           2    32
##  4 F     FALSE           3    15
##  5 F     FALSE           4    11
##  6 F     FALSE           5    10
##  7 F     FALSE           6     9
##  8 F     FALSE           7     7
##  9 F     FALSE           8     9
## 10 F     FALSE           9     4
## # ... with 56 more rows

The number of absences seems to be higher in the heavy drinking group.

A logistical regression model

Mymodel <- glm(high_use ~ failures + absences + famrel + studytime + sex, data = alc, family = "binomial")
summary(Mymodel)
## 
## Call:
## glm(formula = high_use ~ failures + absences + famrel + studytime + 
##     sex, family = "binomial", data = alc)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0557  -0.8196  -0.5880   1.0121   2.1090  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -0.08166    0.64708  -0.126 0.899579    
## failures     0.33723    0.19336   1.744 0.081155 .  
## absences     0.08492    0.02253   3.769 0.000164 ***
## famrel      -0.27215    0.12898  -2.110 0.034855 *  
## studytime   -0.33349    0.16253  -2.052 0.040186 *  
## sexM         0.85149    0.25493   3.340 0.000837 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 465.68  on 381  degrees of freedom
## Residual deviance: 415.39  on 376  degrees of freedom
## AIC: 427.39
## 
## Number of Fisher Scoring iterations: 4
coef(Mymodel)
## (Intercept)    failures    absences      famrel   studytime        sexM 
## -0.08165709  0.33722680  0.08491968 -0.27215425 -0.33349374  0.85149451
OR <- coef(Mymodel) %>% exp
CI <- confint(Mymodel) %>% exp
## Waiting for profiling to be done...
cbind(OR, CI)
##                    OR     2.5 %    97.5 %
## (Intercept) 0.9215879 0.2570726 3.2760808
## failures    1.4010568 0.9596267 2.0600366
## absences    1.0886296 1.0436932 1.1405269
## famrel      0.7617368 0.5907516 0.9813904
## studytime   0.7164164 0.5166676 0.9790799
## sexM        2.3431461 1.4282690 3.8884700

Acording to this model all explanatory variables with the exception of failures, explain alcohol consumption of the students with statistical significance. Even so, failures OD is 1.40 and the interval of confidence is between 0.96 and 2.06 so I dont know how to interpret this when OD over 1 means positive association with high drinking and it would be 1.4 times likely to be a heavy drinker when having one unit more absences.So now I really dont know if I should leave failures from my prediction. Another predictor seems to be absences with oddsratio 1.09, witch means that those with more absences are 1.9 times more likely to be high users. The confidence interval is between 1.04 and 1.14 witch is the narrowest in this model. The OR is over 1 in any case, witch means that absences are positively associated with heavy drinking. Sex seems to be a good explainer so that males are 2.34 times more likely (than females) to be high users of alcohol. Familyrelations and sudytime has weaker OR and the maximum in the interval of confidence is below 1 witch is logical since the better familyrelations you have and the more you study the lower odds for you to be a high user of alcohol.

Prediction

Mymodel <- glm(high_use ~ absences + sex + famrel + studytime, data = alc, family = "binomial")
probabilities <- predict(Mymodel, type = "response")
alc <- mutate(alc, probability = probabilities)
alc <- mutate(alc, prediction = probabilities > 0.5)
table(high_use = alc$high_use, prediction = probabilities > 0.5)
##         prediction
## high_use FALSE TRUE
##    FALSE   250   18
##    TRUE     86   28
g <- ggplot(alc, aes(x = probability, y = high_use, col = prediction))
g + geom_point()

table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
##         prediction
## high_use      FALSE       TRUE        Sum
##    FALSE 0.65445026 0.04712042 0.70157068
##    TRUE  0.22513089 0.07329843 0.29842932
##    Sum   0.87958115 0.12041885 1.00000000
loss_func <- function(class, prob) {
  n_wrong <- abs(class - prob) > 0.5
  mean(n_wrong)
}
loss_func(class = alc$high_use, prob = alc$probability)
## [1] 0.2722513

The propability that the model predicts right FALSE is 0.65 and wronng FALSE 0.05. The propability that the model predicts right TRUE is 0.07 and wrong TRUE 0.23. The training error is 0.27.

cv <- cv.glm(data = alc, cost = loss_func, glmfit = Mymodel, K = 10)
cv$delta
## [1] 0.2827225 0.2853266

The training error is just a little bit bigger than in the model introduced in Datacamp.

Super-bonus

vari27 <- 0.194
vari26 <- 0.199
vari25 <- 0.196
vari24 <- 0.188
vari23 <- 0.191
vari22 <- 0.188
vari21 <- 0.199
vari20 <- 0.196
vari19 <- 0.196
vari18 <- 0.191
vari17 <- 0.196
vari16 <- 0.191
vari15 <- 0.194
vari14 <- 0.188
vari13 <- 0.188
vari12 <- 0.191
vari11 <- 0.196
vari10 <- 0.215
vari9 <- 0.220
vari8 <- 0.223
vari7 <- 0.217
vari6 <- 0.225
vari5 <- 0.262
vari4 <- 0.272
vari3 <- 0.257
vari2 <- 0.283
vari1 <- 0.288

I just put all the variables in the model and started to remove the variables one of a time and then checked out the training error. THe trend here is that less variables, the bigger penalty.

variab <- c(vari1, vari2, vari3, vari4, vari5, vari6, vari7, vari8, vari9, vari10, vari11, vari12, vari13, vari14, vari15, vari16, vari17, vari18, vari19, vari20, vari21, vari22, vari23, vari24, vari25, vari26, vari27)
variables <- c( 1 : 27)
plot(variab, variables)


Clustering and classifications

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
data("Boston")
library("ggplot2")
library("dplyr")
library("GGally")
library("corrplot")
## corrplot 0.84 loaded
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston)
## [1] 506  14
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

The Boston data includes variables describing Boston such as for example what is the degree of criminality, the distribution of age in Boston, lower status of population or pupil-teacher ratio in town. The data has 506 observations and 14 variables.

Bosgraph <- ggpairs(Boston, mapping = aes(alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))
Bosgraph

cor(Boston)
##                crim          zn       indus         chas         nox
## crim     1.00000000 -0.20046922  0.40658341 -0.055891582  0.42097171
## zn      -0.20046922  1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus    0.40658341 -0.53382819  1.00000000  0.062938027  0.76365145
## chas    -0.05589158 -0.04269672  0.06293803  1.000000000  0.09120281
## nox      0.42097171 -0.51660371  0.76365145  0.091202807  1.00000000
## rm      -0.21924670  0.31199059 -0.39167585  0.091251225 -0.30218819
## age      0.35273425 -0.56953734  0.64477851  0.086517774  0.73147010
## dis     -0.37967009  0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad      0.62550515 -0.31194783  0.59512927 -0.007368241  0.61144056
## tax      0.58276431 -0.31456332  0.72076018 -0.035586518  0.66802320
## ptratio  0.28994558 -0.39167855  0.38324756 -0.121515174  0.18893268
## black   -0.38506394  0.17552032 -0.35697654  0.048788485 -0.38005064
## lstat    0.45562148 -0.41299457  0.60379972 -0.053929298  0.59087892
## medv    -0.38830461  0.36044534 -0.48372516  0.175260177 -0.42732077
##                  rm         age         dis          rad         tax
## crim    -0.21924670  0.35273425 -0.37967009  0.625505145  0.58276431
## zn       0.31199059 -0.56953734  0.66440822 -0.311947826 -0.31456332
## indus   -0.39167585  0.64477851 -0.70802699  0.595129275  0.72076018
## chas     0.09125123  0.08651777 -0.09917578 -0.007368241 -0.03558652
## nox     -0.30218819  0.73147010 -0.76923011  0.611440563  0.66802320
## rm       1.00000000 -0.24026493  0.20524621 -0.209846668 -0.29204783
## age     -0.24026493  1.00000000 -0.74788054  0.456022452  0.50645559
## dis      0.20524621 -0.74788054  1.00000000 -0.494587930 -0.53443158
## rad     -0.20984667  0.45602245 -0.49458793  1.000000000  0.91022819
## tax     -0.29204783  0.50645559 -0.53443158  0.910228189  1.00000000
## ptratio -0.35550149  0.26151501 -0.23247054  0.464741179  0.46085304
## black    0.12806864 -0.27353398  0.29151167 -0.444412816 -0.44180801
## lstat   -0.61380827  0.60233853 -0.49699583  0.488676335  0.54399341
## medv     0.69535995 -0.37695457  0.24992873 -0.381626231 -0.46853593
##            ptratio       black      lstat       medv
## crim     0.2899456 -0.38506394  0.4556215 -0.3883046
## zn      -0.3916785  0.17552032 -0.4129946  0.3604453
## indus    0.3832476 -0.35697654  0.6037997 -0.4837252
## chas    -0.1215152  0.04878848 -0.0539293  0.1752602
## nox      0.1889327 -0.38005064  0.5908789 -0.4273208
## rm      -0.3555015  0.12806864 -0.6138083  0.6953599
## age      0.2615150 -0.27353398  0.6023385 -0.3769546
## dis     -0.2324705  0.29151167 -0.4969958  0.2499287
## rad      0.4647412 -0.44441282  0.4886763 -0.3816262
## tax      0.4608530 -0.44180801  0.5439934 -0.4685359
## ptratio  1.0000000 -0.17738330  0.3740443 -0.5077867
## black   -0.1773833  1.00000000 -0.3660869  0.3334608
## lstat    0.3740443 -0.36608690  1.0000000 -0.7376627
## medv    -0.5077867  0.33346082 -0.7376627  1.0000000
cor_matrix<-cor(Boston) 
cor_matrix <- cor_matrix %>% round(digits = 2)
corrplot(cor_matrix, method= "circle")

In this correlation matrix we can see all the variables in the Boston data and their between-correlations. The more darker the color, the stronger the correlation. The shades of red describe negative, and the shades of blue positive correlation. The median value of owner-occupied homes has a strong negative correlation with lower status of population.

Standardizing the data and changing the continuous crime rate -variable in to a categorical one

Next the data will be standardized, ie. it will be scaled so that the column means are subtracted from the corresponding columns and then divided the difference with standard deviation.

boston_scaled <- scale(Boston)
summary(boston_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
class(boston_scaled)
## [1] "matrix"
boston_scaled <- as.data.frame(boston_scaled)
summary(boston_scaled$crim)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
## -0.419367 -0.410563 -0.390280  0.000000  0.007389  9.924110
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label= c("low", "med_low", "med_high", "high"))
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
boston_scaled <- dplyr::select(boston_scaled, -crim)
boston_scaled <- data.frame(boston_scaled, crime)

Splitting the data to train and test sets

n <- nrow(boston_scaled)
ind <- sample(n,  size = n * 0.8)
train <- boston_scaled[ind,]
test <- boston_scaled[-ind,]
correct_classes <- test$crime
test <- dplyr::select(test, -crime)

The LDA model

lda.fit <- lda(crime ~ ., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2400990 0.2475248 0.2524752 0.2599010 
## 
## Group means:
##                  zn      indus        chas        nox         rm
## low       0.8987522 -0.9127563 -0.06938576 -0.8755786  0.4440462
## med_low  -0.1013460 -0.2948651 -0.07547406 -0.5854109 -0.1263624
## med_high -0.3846714  0.2308213  0.26805724  0.3399548  0.1664685
## high     -0.4872402  1.0149946 -0.04735191  1.0589179 -0.3941266
##                 age        dis        rad        tax     ptratio
## low      -0.9109029  0.8742319 -0.7024504 -0.7443069 -0.51279478
## med_low  -0.3780935  0.3842344 -0.5488991 -0.4758427 -0.02287984
## med_high  0.4498005 -0.3753401 -0.4076377 -0.2938312 -0.26928372
## high      0.8171304 -0.8674408  1.6596029  1.5294129  0.80577843
##               black        lstat         medv
## low       0.3761866 -0.770218354  0.521923349
## med_low   0.3189015 -0.134708718 -0.005741625
## med_high  0.1280637 -0.002776611  0.211547573
## high     -0.8233889  0.866909077 -0.660709696
## 
## Coefficients of linear discriminants:
##                 LD1          LD2         LD3
## zn       0.15098162  0.616433374 -0.99529211
## indus    0.03959799 -0.351282500  0.30034887
## chas    -0.07920703 -0.081293764  0.00809093
## nox      0.30427092 -0.756653042 -1.26544764
## rm      -0.10031800 -0.115200141 -0.14579824
## age      0.27395523 -0.428636126 -0.15198464
## dis     -0.09788915 -0.285041855  0.20203735
## rad      3.38775951  0.884606625 -0.09879788
## tax      0.01314084  0.122502402  0.50271858
## ptratio  0.14814605 -0.001459273 -0.12656619
## black   -0.16903069  0.003858969  0.10641987
## lstat    0.22773158 -0.210709250  0.37735323
## medv     0.21485937 -0.361450397 -0.12507104
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9552 0.0343 0.0105
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}
classes <- as.numeric(train$crime)
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1)

lda.pred <- predict(lda.fit, newdata = test)
table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       20       9        1    0
##   med_low    4      14        8    0
##   med_high   0       8       15    1
##   high       0       0        1   21

Here we can see that predicting is quite good since the rates are highest in the groups witch are correctly predicted and no radical errors exist.

dist_eu <- dist(boston_scaled)
## Warning in dist(boston_scaled): NAs introduced by coercion
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1394  3.5267  4.9081  4.9394  6.2421 13.0045
dist_man <- dist(boston_scaled, method = "manhattan")
## Warning in dist(boston_scaled, method = "manhattan"): NAs introduced by
## coercion
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2849  8.8386 13.0300 13.8657 18.0953 46.8948
km <-kmeans(Boston, centers = 2)
km$cluster
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 505 506 
##   1   1
pairs(boston_scaled[1:5], col = km$cluster)

pairs(boston_scaled[6:10], col = km$cluster)

pairs(boston_scaled[11:14], col = km$cluster)

set.seed(123)
k_max <- (k_max = 10)
twcss <- sapply(1:k_max, function(k){kmeans(Boston, k)$tot.withinss})
qplot(x = 1:k_max, y = twcss, geom = 'line')

I tried the model with 5,4,3 and 2 clusters and my interpretation when viewing the plots is that 3 is best but when calculating WCSS it seems that 2 clusters seems to be better choice. Anyhow the tax variable seems to be one clearly with clusters in any case.

Bonus

Bclust <-kmeans(Boston, centers = 3)
Bclust$cluster
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   3   3   1   1   1   1   1   1   3   3   3   3   3   3   3   3   3   3 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   3   3   3   3   3   3   3   3   3   3   1   1   1   1   1   1   1   1 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   1   1   1   1   1   1   1   1   1   1   1   1   3   3   3   3   3   3 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   3   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   1   1   1   1   1   1   1   1   1   3   3   3   3   3   3   3   3 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   3   3   3   3   3   3   3   1   1   1   1   1   1   3   3   3   3   3 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   3   1   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   3   3   3   3   3   3   3   3   3   3   1   1   1   3   3   3   3   3 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   3   3   3   3   1   1   1   3   3   3   3   3   3   3   3   3   3   3 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   1   1   1   1   1   3   3   3   3   1   1   3   3   3   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   3   3   3 
## 505 506 
##   3   3
pairs(boston_scaled[1:5], col = Bclust$cluster)

pairs(boston_scaled[6:10], col = Bclust$cluster)

pairs(boston_scaled[11:14], col = Bclust$cluster)

lda.fit <- lda(Bclust$cluster ~ ., data = boston_scaled)
lda.fit
## Call:
## lda(Bclust$cluster ~ ., data = boston_scaled)
## 
## Prior probabilities of groups:
##         1         2         3 
## 0.1996047 0.2707510 0.5296443 
## 
## Group means:
##            zn      indus          chas        nox         rm        age
## 1 -0.07332724  0.2818828  0.0005392655  0.2816899 -0.1453417  0.1822823
## 2 -0.48724019  1.0662784 -0.0424254043  0.9959393 -0.3962652  0.7599946
## 3  0.27670879 -0.6513071  0.0214843827 -0.6152775  0.2573427 -0.4572006
##          dis        rad         tax    ptratio       black       lstat
## 1 -0.2378455 -0.5418150 -0.01444889 -0.3768823  0.07010933  0.01371321
## 2 -0.8265965  1.5757732  1.53915759  0.8040926 -0.71893398  0.84321670
## 3  0.5121870 -0.6013344 -0.78136288 -0.2690134  0.34109296 -0.43621538
##          medv crimemed_low crimemed_high  crimehigh
## 1 -0.03812375   0.32673267    0.46534653 0.00990099
## 2 -0.68070813   0.03649635    0.04379562 0.91970803
## 3  0.36234147   0.32835821    0.27238806 0.00000000
## 
## Coefficients of linear discriminants:
##                       LD1          LD2
## zn             0.05280738 -0.014188634
## indus          0.52954210  0.136232438
## chas          -0.03744336  0.041429998
## nox            0.20190265 -0.583371775
## rm             0.02768863  0.117101924
## age           -0.01312130  0.006188618
## dis           -0.36742893  0.203235111
## rad            2.17313453  2.225891425
## tax            5.27359727 -2.772125460
## ptratio        0.14183368  0.150571551
## black         -0.04900742  0.092304730
## lstat          0.19460083  0.100047863
## medv           0.32392299 -0.139204299
## crimemed_low  -0.95555999 -0.081053964
## crimemed_high -2.22131989  0.172165534
## crimehigh     -0.91590244  2.292286225
## 
## Proportion of trace:
##    LD1    LD2 
## 0.9855 0.0145
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}
classes <- as.numeric(Bclust$cluster)
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1)

Here we can see that the most influencial linear separatorvariables for the clusters are crimerates, rad and tax. LD1 explains 99% of the between group variance.

Superbonus

lda.fit <- lda(crime ~ ., data = train)
model_predictors <- dplyr::select(train, -crime)
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
library("plotly")
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$crime)
Bclust <-kmeans(Boston, centers = 3)
lda.fit <- lda(Bclust$cluster ~ ., data = boston_scaled)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = Bclust)